{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a8b892c8",
   "metadata": {},
   "source": [
    "Printed and electronic copies of *Modeling and Simulation in Python* are available from [No Starch Press](https://nostarch.com/modeling-and-simulation-python) and [Bookshop.org](https://bookshop.org/p/books/modeling-and-simulation-in-python-allen-b-downey/17836697?ean=9781718502161) and [Amazon](https://amzn.to/3y9UxNb)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "interracial-guitar",
   "metadata": {},
   "source": [
    "# Pharmacokinetics"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "imported-table",
   "metadata": {
    "tags": []
   },
   "source": [
    "*Modeling and Simulation in Python*\n",
    "\n",
    "Copyright 2021 Allen Downey\n",
    "\n",
    "License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "formal-context",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# download modsim.py if necessary\n",
    "\n",
    "from os.path import basename, exists\n",
    "\n",
    "def download(url):\n",
    "    filename = basename(url)\n",
    "    if not exists(filename):\n",
    "        from urllib.request import urlretrieve\n",
    "        local, _ = urlretrieve(url, filename)\n",
    "        print('Downloaded ' + local)\n",
    "    \n",
    "download('https://github.com/AllenDowney/ModSimPy/raw/master/' +\n",
    "         'modsim.py')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "progressive-typing",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# import functions from modsim\n",
    "\n",
    "from modsim import *"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "plastic-trigger",
   "metadata": {
    "tags": []
   },
   "source": [
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "Click here to access the notebooks: <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "european-movement",
   "metadata": {},
   "source": [
    "In this chapter we'll start a new example, a model of how glucose and insulin interact to control blood sugar.\n",
    "We will implement a widely used model called the \"minimal model\" because it is intended to include only the elements essential to explain the observed behavior of the system.\n",
    "\n",
    "This chapter presents the model and some background information we need to understand it.\n",
    "In the next chapter we'll implement the model and compare the results to real data.\n",
    "\n",
    "My presentation in this chapter follows Bergman (2005) \"Minimal Model\"\n",
    "(abstract at <http://modsimpy.com/bergman>, PDF at\n",
    "<http://modsimpy.com/minmod>)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "tamil-helping",
   "metadata": {},
   "source": [
    "## The Minimal Model\n",
    "\n",
    "*Pharmacokinetics* is the study of how drugs and other substances move around the body, react, and are eliminated. In this chapter, I present a widely used pharmacokinetic model of glucose and insulin in the blood stream.\n",
    "\n",
    "*Glucose* is a form of sugar that circulates in the blood of animals; it is used as fuel for muscles, the brain, and other organs. The concentration of blood sugar is controlled by the hormone system, and especially by *insulin*, which is produced by the pancreas and has the effect of reducing blood sugar.\n",
    "\n",
    "In people with normal pancreatic function, the hormone system maintains *homeostasis*; that is, it keeps the concentration of blood sugar in a range that is neither too high or too low.\n",
    "\n",
    "But if the pancreas does not produce enough insulin, or if the cells\n",
    "that should respond to insulin become insensitive, blood sugar can\n",
    "become elevated, a condition called *hyperglycemia*. Long term, severe hyperglycemia is the defining symptom of *diabetes mellitus*, a serious disease that affects almost 10% of the population in the U.S. (see <http://modsimpy.com/cdc>)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "sharp-yukon",
   "metadata": {},
   "source": [
    "A widely used test for hyperglycemia and diabetes is the\n",
    "frequently sampled intravenous glucose tolerance test (FSIGT), in which glucose is injected into the blood stream of a fasting subject (someone who has not eaten recently); then blood samples are collected at intervals of 2--10 minutes for 3 hours. The samples are analyzed to measure the concentrations of glucose and insulin.\n",
    "\n",
    "Using these measurements, we can estimate several parameters of\n",
    "the subject's response; the most important is a parameter denoted $S_I$, which quantifies the effect of insulin on the rate of reduction in blood sugar."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "round-roommate",
   "metadata": {},
   "source": [
    "## The Glucose Minimal Model\n",
    "\n",
    "The minimal model, as proposed by Bergman, Ider, Bowden, and\n",
    "Cobelli, consists of two parts: the glucose model and the insulin model. I will present an implementation of the glucose model; as a case study, you will have the chance to implement the insulin model.\n",
    "\n",
    "The original model was developed in the 1970s; since then, many\n",
    "variations and extensions have been proposed. Bergman's comments on the development of the model provide insight into their process:\n",
    "\n",
    "> We applied the principle of Occam's Razor, i.e. by asking what was the simplest model based upon known physiology that could account for the insulin-glucose relationship revealed in the data. Such a model must be simple enough to account totally for the measured glucose (given the insulin input), yet it must be possible, using mathematical techniques, to estimate all the characteristic parameters of the model from a single data set (thus avoiding unverifiable assumptions)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "accompanied-battery",
   "metadata": {},
   "source": [
    "The most useful models are the ones that achieve this balance: including enough realism to capture the essential features of the system without so much complexity that they are impractical. In this example, the practical limit is the ability to estimate the parameters of the model using data, and to interpret the parameters meaningfully.\n",
    "\n",
    "Bergman discusses the features he and his colleagues thought were\n",
    "essential:\n",
    "\n",
    "> 1. Glucose, once elevated by injection, returns to basal level due to two effects: the effect of glucose itself to normalize its own concentration \\[...\\] as well as the catalytic effect of insulin to allow glucose to self-normalize.\n",
    "> 2. Also, we discovered that the effect of insulin on net glucose disappearance must be sluggish --- that is, that insulin acts slowly because insulin must first move from plasma to a remote compartment \\[...\\] to exert its action on glucose disposal.\n",
    "\n",
    "To paraphrase the second point, the effect of insulin on glucose\n",
    "disposal, as seen in the data, happens more slowly than we would expect if it depended primarily on the concentration of insulin in the blood. Bergman's group hypothesized that insulin must move relatively slowly from the blood to a remote compartment where it has its effect."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "growing-logistics",
   "metadata": {},
   "source": [
    "At the time, the \"remote compartment\" was a modeling abstraction that\n",
    "might, or might not, represent something physical. Later, according to\n",
    "Bergman, it was \"shown to be interstitial fluid\", that is, the fluid\n",
    "that surrounds tissue cells. \n",
    "\n",
    "In the history of mathematical modeling, it is common for hypothetical entities, added to models to achieve particular effects, to be found later to correspond to physical entities.  One notable example is the gene, which was defined as an inheritable unit several decades before we learned that genes are encoded in DNA  (see <https://en.wikipedia.org/wiki/Gene#Discovery_of_discrete_inherited_units>)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bottom-extent",
   "metadata": {},
   "source": [
    "The glucose model consists of two differential equations:\n",
    "\n",
    "$$\\frac{dG}{dt} = -k_1 \\left[ G(t) - G_b \\right] - X(t) G(t)$$\n",
    "\n",
    "$$\\frac{dX}{dt} = k_3 \\left[I(t) - I_b \\right] - k_2 X(t)$$ \n",
    "\n",
    "where\n",
    "\n",
    "-   $G$ is the concentration of blood glucose as a function of time and $dG/dt$ is its rate of change.\n",
    "\n",
    "-   $X$ is the concentration of insulin in the tissue fluid as a\n",
    "    function of time, and $dX/dt$ is its rate of change.\n",
    "\n",
    "-   $I$ is the concentration of insulin in the blood as a function of\n",
    "    time, which is taken as an input into the model, based on\n",
    "    measurements.\n",
    "\n",
    "-   $G_b$ is the basal concentration of blood glucose and $I_b$ is the\n",
    "    basal concentration of blood insulin, that is, the concentrations at equilibrium. Both are constants estimated from measurements at the\n",
    "    beginning or end of the test.\n",
    "\n",
    "-   $k_1$, $k_2$, and $k_3$ are positive-valued parameters that control the rates of appearance and disappearance for glucose and insulin."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dutch-retailer",
   "metadata": {},
   "source": [
    "We can interpret the terms in the equations one by one:\n",
    "\n",
    "-   $-k_1 \\left[ G(t) - G_b \\right]$ is the rate of glucose\n",
    "    disappearance due to the effect of glucose itself. When $G(t)$ is\n",
    "    above basal level, $G_b$, this term is negative; when $G(t)$ is\n",
    "    below basal level this term is positive. So in the absence of\n",
    "    insulin, this term tends to restore blood glucose to basal level.\n",
    "\n",
    "-   $-X(t) G(t)$ models the interaction of glucose and insulin in tissue\n",
    "    fluid, so the rate increases as either $X$ or $G$ increases. This\n",
    "    term does not require a rate parameter because the units of $X$ are\n",
    "    unspecified; we can consider $X$ to be in whatever units make the\n",
    "    parameter of this term 1.\n",
    "\n",
    "-   $k_3 \\left[ I(t) - I_b \\right]$ is the rate at which insulin diffuses between blood and tissue fluid. When $I(t)$ is above basal level, insulin diffuses from the blood into the tissue fluid. When $I(t)$ is below basal level, insulin diffuses from tissue to the\n",
    "    blood.\n",
    "\n",
    "-   $-k_2 X(t)$ is the rate of insulin disappearance in tissue fluid as it is consumed or broken down."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "regional-receptor",
   "metadata": {},
   "source": [
    "The initial state of the model is $X(0) = I_b$ and $G(0) = G_0$, where\n",
    "$G_0$ is a constant that represents the concentration of blood sugar\n",
    "immediately after the injection. In theory we could estimate $G_0$ based on measurements, but in practice it takes time for the injected glucose to spread through the blood volume. Since $G_0$ is not measurable, it is treated as a *free parameter* of the model, which means that we are free to choose it to fit the data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apart-giant",
   "metadata": {},
   "source": [
    "## Getting the Data\n",
    "\n",
    "To develop and test the model, we'll use data from Pacini and Bergman, \"MINMOD: a computer program to calculate insulin sensitivity and pancreatic responsivity from the frequently sampled intravenous glucose tolerance test\", *Computer Methods and Programs in Biomedicine*, 1986 (see <https://www.researchgate.net/publication/13707725_Insulin_sensitivity_and_glucose_effectiveness_Minimal_model_analysis_of_regular_and_insulin-modified_FSIGT>)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "exact-heating",
   "metadata": {
    "tags": []
   },
   "source": [
    "The following cell downloads the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "mental-wrong",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "download('https://github.com/AllenDowney/ModSim/raw/main/data/' +\n",
    "         'glucose_insulin.csv')\n",
    "\n",
    "'https://github.com/AllenDowney/ModSim/raw/main/data/glucose_insulin.csv'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dressed-regard",
   "metadata": {},
   "source": [
    "We can use Pandas to read the data file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cosmetic-matrix",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pandas import read_csv\n",
    "\n",
    "data = read_csv('glucose_insulin.csv', index_col='time')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "written-beast",
   "metadata": {},
   "source": [
    "Here are the first few rows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "naval-geology",
   "metadata": {},
   "outputs": [],
   "source": [
    "data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "close-payday",
   "metadata": {},
   "source": [
    "`data` has two columns: `glucose` is the concentration of blood glucose in mg/dL; `insulin` is the concentration of insulin in the blood in $\\mu$U/mL (a medical \"unit\", denoted U, is an amount defined by convention in context). The index is time in minutes.\n",
    "\n",
    "This dataset represents glucose and insulin concentrations over\n",
    "182 min for a subject with normal insulin production and sensitivity."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "burning-valuable",
   "metadata": {},
   "source": [
    "## Interpolation\n",
    "\n",
    "Before we are ready to implement the model, there's one problem we have to solve. In the differential equations, $I$ is a function that can be evaluated at any time $t$. But in the `DataFrame`, we have measurements only at discrete times. The solution is interpolation, which estimates the value of $I$ for values of $t$ between the measurements.\n",
    "\n",
    "To interpolate the values in `I`, we can use `interpolate`, which takes a `Series` as a parameter and returns a function. That's right, I said it returns a *function*.\n",
    "We can call `interpolate` like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "terminal-teaching",
   "metadata": {},
   "outputs": [],
   "source": [
    "I = interpolate(data.insulin)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "banner-shakespeare",
   "metadata": {},
   "source": [
    "The result is a function we can call like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "intense-thursday",
   "metadata": {},
   "outputs": [],
   "source": [
    "I(18)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "severe-desire",
   "metadata": {},
   "source": [
    "In this example the interpolated value is about 31.7, which is a linear interpolation between the actual measurements at `t=16` and `t=19`.\n",
    "We can also pass an array as an argument to `I`.  Here's an array of equally-spaced values from `t_0` to `t_end`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "least-pattern",
   "metadata": {},
   "outputs": [],
   "source": [
    "t_0 = data.index[0]\n",
    "t_end = data.index[-1]\n",
    "t_array = linrange(t_0, t_end)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "empirical-tackle",
   "metadata": {},
   "source": [
    "And here are the corresponding values of `I`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "mounted-venice",
   "metadata": {},
   "outputs": [],
   "source": [
    "I_array = I(t_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "searching-respect",
   "metadata": {},
   "source": [
    "We can use `make_series` to put the results in a Pandas `Series`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "affecting-response",
   "metadata": {},
   "outputs": [],
   "source": [
    "I_series = make_series(t_array, I_array)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "insured-textbook",
   "metadata": {},
   "source": [
    "Here's what the interpolated values look like along with the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "engaging-watershed",
   "metadata": {},
   "outputs": [],
   "source": [
    "data.insulin.plot(style='o', color='C2', label='insulin data')\n",
    "I_series.plot(color='C2', label='interpolation')\n",
    "\n",
    "decorate(xlabel='Time (min)',\n",
    "         ylabel='Concentration (μU/mL)')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "blond-prince",
   "metadata": {},
   "source": [
    "Linear interpolation connects the dots with straight lines, and for this dataset that's probably good enough. As an exercise, below, you can try out other kinds of interpolation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adopted-locking",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "This chapter introduces a model of the interaction between glucose and insulin in the blood stream.\n",
    "And it introduces a new tool, interpolation, which we'll need to implement the model.\n",
    "\n",
    "In the next chapter, we will use measured concentrations of insulin to simulate the glucose-insulin system, and compare the results to measured concentrations of glucose.\n",
    "\n",
    "Then you'll have a chance to implement the second part of the model, which uses measured concentrations of glucose to simulate the insulin response, and compare the results to the data."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "floppy-store",
   "metadata": {},
   "source": [
    "## Exercises\n",
    "\n",
    "This chapter is available as a Jupyter notebook where you can read the text, run the code, and work on the exercises. \n",
    "You can access the notebooks at <https://allendowney.github.io/ModSimPy/>."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "hungarian-newman",
   "metadata": {},
   "source": [
    "### Exercise 1\n",
    "\n",
    "`interpolate` is a wrapper for the SciPy function `interp1d`.\n",
    "Read the documentation of `interp1d` at <http://modsimpy.com/interp>.\n",
    "\n",
    "In particular, notice the `kind` argument, which specifies a kind of interpolation.\n",
    "The default is linear interpolation, which connects the data points with straight lines.\n",
    "\n",
    "Pass a keyword argument to `interpolate` to specify one of the other kinds of interpolation and plot the results."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "endless-network",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "entire-concern",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Here's the plotting code again.\n",
    "\n",
    "data.insulin.plot(style='o', color='C2', label='insulin data')\n",
    "I_series.plot(color='C2', label='interpolation')\n",
    "\n",
    "decorate(xlabel='Time (min)',\n",
    "         ylabel='Concentration (μU/mL)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "invisible-activation",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "furnished-recognition",
   "metadata": {},
   "source": [
    "### Exercise 2\n",
    "\n",
    " Interpolate the glucose data and generate a plot, similar to the previous one, that shows the data points and the interpolated curve evaluated at the time values in `t_array`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "representative-acquisition",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "rocky-sydney",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Solution goes here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "essential-fishing",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "celltoolbar": "Tags",
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
